﻿/*
*   学员信息页面
*/
angular.module('jisuStuHome').controller('stuInfo', ['FileUploader', '$scope', 'StuRequestTrain', 'requestStatisticService', 'sysUserInfo', 'Msg', 'MsgCon', 'T', 'CheckID', function (FileUploader, $scope, ST, RSS, sysUserInfo, Msg, MsgCon, T, CheckID) {

    // 获取人员基本信息
    $scope.stuUserinfoOld = sysUserInfo.getuserinfo();
    $scope.needSaveImg = false; //不需要保存图片
    //初始化，否则拼接有underfined
    $scope.stuUserinfoOld.orgStuStr = "";
    $scope.stuUserinfoOld.roleStuStr = "";
    $scope.stuUserinfoOld.groupStuStr = "";

    if ($scope.stuUserinfoOld.userOrgList != undefined && $scope.stuUserinfoOld.userOrgList.length > 0) {
        // 组织结构 ID 字符串
        for (var i = 0; i < $scope.stuUserinfoOld.userOrgList.length; i++) {
            $scope.stuUserinfoOld.orgStuStr += $scope.stuUserinfoOld.userOrgList[i]["organization_Name"] + ",";
        }
        $scope.stuUserinfoOld.orgStuStr = $scope.stuUserinfoOld.orgStuStr.substr(0, $scope.stuUserinfoOld.orgStuStr.length - 1);
    }
    // 权限 ID 字符串
    if ($scope.stuUserinfoOld.userRoleList != undefined && $scope.stuUserinfoOld.userRoleList.length > 0) {
        for (var i = 0; i < $scope.stuUserinfoOld.userRoleList.length; i++) {
            $scope.stuUserinfoOld.roleStuStr += $scope.stuUserinfoOld.userRoleList[i]["roles_Name"] + ",";
        }
        $scope.stuUserinfoOld.roleStuStr = $scope.stuUserinfoOld.roleStuStr.substr(0, $scope.stuUserinfoOld.roleStuStr.length - 1);
    }
    // 用户组 ID 字符串
    if ($scope.stuUserinfoOld.userGroupList != undefined && $scope.stuUserinfoOld.userGroupList.length > 0) {
        for (var i = 0; i < $scope.stuUserinfoOld.userGroupList.length; i++) {
            $scope.stuUserinfoOld.groupStuStr += $scope.stuUserinfoOld.userGroupList[i]["userGroup_Name"] + ",";
        }
        $scope.stuUserinfoOld.groupStuStr = $scope.stuUserinfoOld.groupStuStr.substr(0, $scope.stuUserinfoOld.groupStuStr.length - 1);
    }
    // 处理完毕赋值
    $scope.stuUserinfo = $scope.stuUserinfoOld;
    // loading
    $scope.stuUserinfoLoading = false;
    // 保存信息
    console.log($scope.stuUserinfoOld);
    $scope.saveUserinfo = function () {

        var myreg = /^1[0-9][0-9]\d{4,8}$/;
        if (!myreg.test($scope.stuUserinfo.phone) || $scope.stuUserinfo.phone.length != 11) {
            Msg.warning("请输入正确的手机号！");
            return;
        }
        if ($scope.stuUserinfo.userName.length <= 0) {
            Msg.warning("请输入正确的姓名！");
            return;
        }
        if ($scope.stuUserinfo.identifyCard == undefined || $scope.stuUserinfo.identifyCard == null || $scope.stuUserinfo.identifyCard.length < 18) {
            Msg.warning("请输入正确身份证号码！");
            return;
        }
        if ($scope.stuUserinfo.user_Sex == undefined || $scope.stuUserinfo.user_Sex == null || $scope.stuUserinfo.user_Sex.length <= 0) {
            Msg.warning("请选择您的性别！");
            return;
        }
        if ($scope.stuUserinfo.userContact.education == undefined || $scope.stuUserinfo.userContact.education == null || $scope.stuUserinfo.userContact.education.length <= 0) {
            Msg.warning("请选择您的学历！");
            return;
        }

        $scope.saveInfo();

    }
    $scope.saveInfo = function () {
        $scope.stuUserinfoLoading = true;
        //是否操作了头像
        if ($scope.stuUserinfo.user_Img.indexOf("data:") != -1) {
            $scope.resUrl = $scope.stuUserinfo.user_Img;
            var params = { blob: $scope.resUrl, userid: $scope.stuUserinfo.user_ID };
            RSS.uploadCover(params).success(function (data) {
                if (data.errorcode == 0) {
                    Msg.success('上传头像成功！');

                    $scope.stuUserinfo.user_Img = data.errormsg + "?time=" + new Date();
                    $scope.SaveFunction();
                } else {
                    Msg.error('请求失败！');
                }
                //响应成功操作
            }).error(function (data) {
                Msg.error('连接服务器失败！');
                //响应失败（响应以错误状态返回）操作
            })
        } else {
            $scope.SaveFunction();
        }
    }
    //保存用户
    $scope.SaveFunction = function () {


        $scope.stuUserinfo.userContact.birthDate = document.getElementById("birthDate").value;
        // 请求参数 
        $scope.params = {
            userid: $scope.stuUserinfo.user_ID,
            userImg: $scope.stuUserinfo.user_Img,
            email: $scope.stuUserinfo.email, // 邮箱

            usersex: $scope.stuUserinfo.user_Sex, // 性别
            identifyCard: $scope.stuUserinfo.identifyCard, // 身份证号
            phone: $scope.stuUserinfo.phone, // 手机号        
            education: $scope.stuUserinfo.userContact.education, // 学历

            telephone: $scope.stuUserinfo.userContact.telephone, //电话
            duties: $scope.stuUserinfo.userContact.duties, // 职务
            birthDate: $scope.stuUserinfo.userContact.birthDate, // 出身日期
            servants: $scope.stuUserinfo.userContact.servants, // 是否公务员
            nation: $scope.stuUserinfo.userContact.nation, // 名族
            political: $scope.stuUserinfo.userContact.political// 政治面貌
        }


        // 发送请求
        ST.updateStuInfo($scope.params).then(function (response) {
            $scope.stuUserinfoLoading = false;
            if (response.errorcode == "0") {
                Msg.success("提示", "保存成功!");
                $scope.userinfo = sysUserInfo.getuserinfo();
                $scope.userinfo.email = $scope.params.email;

                $scope.userinfo.user_Sex = $scope.params.usersex;
                $scope.userinfo.phone = $scope.params.phone;
                $scope.userinfo.identifyCard = $scope.params.identifyCard;

                $scope.stuUserinfo.user_Img = $scope.stuUserinfo.user_Img.split("?")[0];
                $scope.userinfo.user_Img = $scope.stuUserinfo.user_Img + "?time=" + new Date();
                var concat = $scope.stuUserinfo.userContact;
                $scope.userinfo.userContact = concat;
                //把对象放入缓存
                sysUserInfo.setuserinfo($scope.userinfo);

            } else {
                Msg.error("错误", "保存失败!")
            }
        }, function errorCallback() {
            $scope.stuUserinfoLoading = false;
            console.log("连接服务器失败！");
        });

    }
    //保存用户头像
    $scope.SaveFun = function () {
        $scope.addinfo();
    }
    //保存人员头像框
    $scope.saveImgCode = function () {
        $scope.needSaveImg = true; //需要保存图片
        $scope.headShow = false;
    }
    // 打开人员头像截取
    $scope.headShow = false;
    $scope.imgUrl = "";
    $scope.resUrl = ""; //人员头像base64码
    $scope.openCropImg = function () {
        $scope.headShow = true;
        console.log($scope.stuUserinfo.user_Img);
        $scope.imgUrl = $scope.stuUserinfo.user_Img;
    }
    /*****************************************************************************************************************/


    /**  
    * 将以base64的图片url数据转换为Blob  
    * @param urlData  
    *            用url方式表示的base64图片数据  
    */
    $scope.getfileByBase64 = function convertBase64UrlToBlob(urlData) {

        var bytes = window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte  

        //处理异常,将ascii码小于0的转换为大于0  
        var ab = new ArrayBuffer(bytes.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
        }

        return new Blob([ab], { type: 'image/png' });
    }
    /***************************************日志**********************************/
    $scope.logList = [];
    $scope.logParams = {
        userId: sysUserInfo.getuserinfo().user_ID,
        pageIndex: "1",
        pageSize: "5",
        pageCount: 0
    }
    $scope.getLogList = function () {
        ST.personnelLogGetList($scope.logParams).then(function (response) {
            if (response.errorcode == "0") {
                $scope.logList = response.datas;
                $scope.logParams.pageCount = response.numCount;
            }
        });
    }
    $scope.nextLogList = function () {
        if ($scope.logParams.pageIndex * 5 > $scope.logParams.pageCount || $scope.logParams.pageCount == 0) {
            Msg.info("已经是最后一条记录了！");
            return;
        }
        $scope.logParams.pageIndex = parseInt($scope.logParams.pageIndex) + 1;
        ST.personnelLogGetList($scope.logParams).then(function (response) {
            if (response.errorcode == "0") {
                $scope.logList = $scope.logList.concat(response.datas);
            }
        });
    }
    //$scope.getLogList();
    /**********************************************************2018-8-28******************************************************/
    //政治面貌集合
    $scope.politicalList = [
        { name: "中共党员", value: "1" },
        { name: "共青团员", value: "2" },
        { name: "民主党派", value: "3" },
        { name: "群众", value: "4" }
    ];
    /**********************************************************2018-8-28******************************************************/
    //政治面貌集合
    $scope.politicalList = [
        { name: "中共党员", value: "1" },
        { name: "共青团员", value: "2" },
        { name: "民主党派", value: "3" },
        { name: "群众", value: "4" }
    ];
    //切换性别
    $scope.checkedSexType = function (index) {
        $scope.stuUserinfo.user_Sex = index;
    }
    //切换公务员
    $scope.checkedUserType = function (index) {
        $scope.stuUserinfo.userContact.servants = index;
    }


    //获取出身日期
    $scope.getDate = function () {
        $scope.stuUserinfo.userContact.birthDate = document.getElementById("birthDate").value;
    }



    
	 /***********************************************组织架构选择器*****************************************************/
    $scope.mousePosition = function (ev) {
        if (!ev) {
            ev = window.event;
        }

        if (ev.type != "click") {
            return;
        }
        var width = 0;
        var height = 0;
        if (ev.pageX || ev.pageY) {//firefox、chrome等浏览器
            if (document.documentElement.clientWidth - ev.pageX < 450) {
                width = ev.pageX - (450 - (document.documentElement.clientWidth - ev.pageX)) - 20;
            } else {
                width = ev.pageX;
            }
            if (document.documentElement.clientHeight - ev.pageY < 480) {
                height = ev.pageY - (480 - (document.documentElement.clientHeight - ev.pageY)) - 20;
            } else {
                height = ev.pageY;
            }

            return { "left": width + "px", "top": height + "px", "position": "fixed" };
        }

        return {// IE浏览器
            "left": ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            "top": ev.clientY + document.body.scrollTop - document.body.clientTop
        };
    }
    // 人员选择器                
   $scope.stuData = {
        menu: [{ "id": "Org" }],
        ApiOpen: false,
        windowModal: 1,
        style: "",powerLV :"2", 
        ViceuserOrgList: [],
        searchType: [],  //初始化教师查询
        DB: "0",
        DBdata: [],
        userOrgList: [],
    }
    // 选择用户群
    $scope.selOrg = function(event){
        $scope.stuData.style=$scope.mousePosition(event);
        $scope.stuData.ApiOpen = true;          
        $scope.stuData.userOrgList=[];                    
    }
    //选择一个后关闭
     $scope.$watch('stuData.userOrgList', function (newValue, oldValue, scope) {
        if($scope.stuData.userOrgList.length>0){
            var validate=false;
            if ($scope.stuUserinfoOld.userOrgList != undefined && $scope.stuUserinfoOld.userOrgList.length > 0) {
                $scope.stuUserinfoOld.userOrgList.forEach(function(data,index){
                    if(data.organization_ID==$scope.stuData.userOrgList[0].organization_ID){
                        validate=true;
                    }
                });
            }
             if(validate){
                    Msg.warning("您已在当前组织架构里，请重新选择！");
                    $scope.stuData.userOrgList=[];
            }else{
                $scope.addParam.newDepartmentID=$scope.stuData.userOrgList[0].organization_ID;
                $scope.addParam.newDepartmentName=$scope.stuData.userOrgList[0].organization_Name;
                $scope.stuData.ApiOpen = false;   
            }
        }
     },true); 
    /***********************************************组织架构变更业务***************************************************/
    //初始化新增的参数
    $scope.initAddParam=function(){
        $scope.addParam={
            oldDepartmentID:"",
            oldDepartmentName:"",
            newDepartmentID:"",
            newDepartmentName:"",
            createOrgId:sysUserInfo.getuserinfo().organization_ID,
            createOrgName:sysUserInfo.getuserinfo().organization_Name,
            createUserId:sysUserInfo.getuserinfo().user_ID,
            createUserName:sysUserInfo.getuserinfo().user_Name,
            createUserImg:sysUserInfo.getuserinfo().user_Img,
            remark:""

        };
    }

    $scope.showExaminerUser = false; //弹框的显示
    $scope.showNoAuditList = false; //未审核通过的信息

    $scope.oldOrgInfo = {}; //当前变更的组织架构
    $scope.noList=[];
    //打开弹框
    $scope.openForm = function (item) {
        if (item != undefined) {
            $scope.stuUserinfoLoading=true;
            //查找当前部门是否有审核信息
             ST.stuFindAuditByOrgId({ orgid:sysUserInfo.getuserinfo().organization_ID,userid:sysUserInfo.getuserinfo().user_ID,departmentid:item.organization_ID}).then(function (data) {
                $scope.stuUserinfoLoading=false;
                if(data.errorcode==0){
                    
                    //找到未完成的审核
                    if(data.datas!=undefined&&data.datas!=null&&data.datas.length>0){
                        $scope.noList=data.datas;
                        $scope.showNoAuditList=true;
                    //未找到，就可以申请
                    }else{
                        $scope.oldOrgInfo = item;
                        $scope.initAddParam();
                        $scope.addParam.oldDepartmentID=item.organization_ID;
                        $scope.addParam.oldDepartmentName=item.organization_Name;
                        $scope.showExaminerUser=true;
                    }
                }else{
                    Msg.warning("数据异常！");
                }
            }, function (data) {
                $scope.stuUserinfoLoading=false;
                Msg.error('连接服务器失败！');
            })
            
        }else{
            $scope.showExaminerUser = false;
        }

    }
    $scope.islivebtnload=false;
    //提交申请
    $scope.saveAudit = function () {
        
        if($scope.addParam.newDepartmentID.length<=0){
            Msg.warning("请选择要变更的部门！");
            return;
        }
        $scope.islivebtnload=true;
        ST.saveOrgAudit({ data:JSON.stringify($scope.addParam)}).then(function (data) {
            $scope.islivebtnload=false;
            Msg.success("提示","申请提交成功！请耐心等待管理员"); 
           $scope.showExaminerUser = false;
        }, function (data) {
            $scope.islivebtnload=false;
            Msg.error('连接服务器失败！');
        })
    }

    $scope.closeAuditList=function(){
        $scope.showNoAuditList=false;
    }
} ]);

